package com.jy.modules.cims.component.api;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.component.common.service.TCMmContractService;
import com.jy.modules.cims.component.quota.ICQuota;
import com.jy.modules.cims.data.common.dto.TCMmContractDTO;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dao.QuotaDao;
import com.jy.modules.cims.data.dto.QuotaDto;
import com.jy.modules.cims.data.interact.api.ResponseMessageEnum;
import com.jy.modules.cims.data.interact.api.request.RequestQuotaApplyDTO;
import com.jy.modules.cims.data.interact.api.response.ResponseQuotaApplyDTO;

/**
 * @description 捷越接受外围系统额度业务处理组件。
 * @author shengzhoutao
 * 
 */
@Service("com.jy.modules.cims.component.api.CReceiveQuotaImpl")
public class CReceiveQuotaImpl {
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmContractService")
	public TCMmContractService tcMmContractService;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.quota.CQuotaImpl")
	public ICQuota iCQuota;

	@Autowired
	public QuotaDao quotaDao;

	@Autowired
	public DealDao dealDao;

	/**
	 * @description 接受商户发送贷款转出额度申请/债权转让额度申请业务请求
	 * @param
	 * @return
	 * @throws Exception
	 * @author yujiazheng
	 * @Date
	 */
	public ResponseQuotaApplyDTO applyQuota(final RequestQuotaApplyDTO content) throws Exception {

		ResponseQuotaApplyDTO response = new ResponseQuotaApplyDTO();

		String contractCode = content.getContractCode();// 合约编号
		BigDecimal quotaSum = content.getQuotaSum();// 申请金额
		Date startDate = content.getStartDate();// 起始日期
		Date invalidDate = content.getInvalidDate();// 失效日期
		String quotaType = ""; // 额度申请类型
		String dealType = "";// 交易类型
		String cooperorgCode = "";// 合作机构编号
		String quotaCode = "";// 额度申请编号
		String quotaStatus = CimsConstant.QUOTA_STATUS_WAIT_AUDIT;
		;// 额度申请状态
		String validateState = CimsConstant.DATE_STATUS_VALID;// 数据有效性

		// step1-1:基本信息校验1（金额、日期校验）
		if (ResponseMessageEnum.FAILURE.getResult().equals(baseCheck(startDate, invalidDate, quotaSum).getResult())) {
			return baseCheck(startDate, invalidDate, quotaSum);
		}

		// step1-2:查询合约信息
		List<TCMmContractDTO> tcMmContractDTOs = null;
		try {
			tcMmContractDTOs = searchTCMmContract(contractCode);
		} catch (Exception e) {
			response.setMessage("查询合约信息报错，请联系系统人员！");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}

		// step1-3:基本信息校验 2 （合约信息校验）
		if (ResponseMessageEnum.FAILURE.getResult().equals(baseCheck2(tcMmContractDTOs, contractCode).getResult())) {
			return baseCheck2(tcMmContractDTOs, contractCode);
		}

		// step1-4:获取业务类型、合作机构编号
		dealType = tcMmContractDTOs.get(0).getDealType();
		cooperorgCode = tcMmContractDTOs.get(0).getCooperorgCode();

		// step2:具体业务流程处理
		if (CimsConstant.DEAL_TYPE_LOAN_OUT.equals(dealType)) {// 贷款转出
			// step2-1: 贷款转出额度申请业务流程处理
			quotaCode = iCQuota.createQuotaCode();
			quotaType = CimsConstant.QUOTATYPE_LOAN;
		} else if (CimsConstant.DEAL_TYPE_CREDIT_OUT.equals(dealType)) {// 债权转让
			// step2-2: 债权转出业额度申请业务流程处理
			quotaCode = iCQuota.createQuotaCode();
			quotaType = CimsConstant.QUOTATYPE_CR;
		} else { // 无效业务类型
			response.setMessage("无效业务类型【" + quotaType + "】,请联系系统人员！");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}

		try {
			// 保存额度申请信息
			insertQuotaInfo(quotaCode, quotaSum, startDate, invalidDate, quotaType, contractCode, cooperorgCode, quotaStatus, validateState);
		} catch (Exception e) {
			response.setMessage("保存额度申请信息失败！");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}

		// step3:返回信息组装
		response.setId(quotaCode);
		response.setMessage("额度申请交易成功！结算申请编号为:" + quotaCode);
		response.setResult(ResponseMessageEnum.SUCCESS.getResult());// 交易成功

		return response;
	}

	/**
	 * 获取当前日期 格式为：yyyy-MM-dd
	 * 
	 * @return Date
	 * @throws ParseException
	 */
	private Date getNowDate() throws ParseException {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String str = formatter.format(currentTime);
		return DateTimeUtils.parseDate(str, "yyyy-MM-dd");
	}

	/**
	 * 贷款转出额度申请-基本校验1 未查询数据库前校验
	 * 
	 * @param startDate
	 * @param invalidDate
	 * @param quotaSum
	 * @return
	 */
	private ResponseQuotaApplyDTO baseCheck(Date startDate, Date invalidDate, BigDecimal quotaSum) {
		ResponseQuotaApplyDTO response = new ResponseQuotaApplyDTO();
		java.util.Date nowdate;// 系统日期
		try {
			nowdate = getNowDate();
		} catch (ParseException e) {
			response.setMessage("获取系统日期失败!");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}
		// 【起始日期】小于等于【失效日期】
		if (DateTimeUtils.dateCompare(startDate, invalidDate)) {
			response.setMessage("失效日期:【" + DateTimeUtils.formatDate(invalidDate, "yyyy-MM-dd") + "】大于等于起始日期:【"
					+ DateTimeUtils.formatDate(startDate, "yyyy-MM-dd") + "】!");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}
		// 【系统日期】 加30天
		Date tempDate = DateTimeUtils.addDays(nowdate, 30);

		// 【失效时间】不能大于【系统日期】30天
		if (DateTimeUtils.dateCompare(invalidDate, tempDate)) {
			response.setMessage("失效日期:【" + DateTimeUtils.formatDate(invalidDate, "yyyy-MM-dd") + "】不能大于系统日期:【"
					+ DateTimeUtils.formatDate(nowdate, "yyyy-MM-dd") + "】30日!");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}

		// 【申请金额】 1、大于0元 2、长度为18位 保留2位小数
		if (quotaSum.compareTo(BigDecimal.ZERO) > 0) {
			String tempSum = quotaSum.toString();
			if (tempSum.indexOf(".") > 0) {
				int iLength = tempSum.split("\\.")[0].length();
				int sLength = tempSum.split("\\.")[1].length();
				if (iLength > 16 || sLength > 2) {
					response.setMessage("申请金额:【" + quotaSum + "】应为长度为18位包含16位整数,2位小数！");
					response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
					return response;
				}
			} else {
				int iLength = tempSum.length();
				if (iLength > 16) {
					response.setMessage("申请金额:【" + quotaSum + "】应为长度为18位包含16位整数,2位小数！");
					response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
					return response;
				}
			}

		} else {
			response.setMessage("申请金额:【" + quotaSum + "】须大于0元！");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}

		return response;
	}

	/**
	 * @description 贷款转出额度申请-基本校验2 查询数据库后校验
	 * 
	 * @param tcMmContractDTOs
	 * @param contractCode
	 * @return
	 */
	private ResponseQuotaApplyDTO baseCheck2(List<TCMmContractDTO> tcMmContractDTOs, String contractCode) {
		ResponseQuotaApplyDTO response = new ResponseQuotaApplyDTO();
		// 合约编号存性校验、合约编号唯一性校验
		if (tcMmContractDTOs == null || tcMmContractDTOs.size() < 1) {
			response.setMessage("合约编号:【" + contractCode + "】不存在,请联系系统人员！");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		} else if (tcMmContractDTOs.size() > 1) {
			response.setMessage("合约编号:【" + contractCode + "】不唯一,请联系系统人员！");
			response.setResult(ResponseMessageEnum.FAILURE.getResult());// 交易失败
			return response;
		}
		return response;
	}

	/**
	 * @description 根据合约编号查询合约信息
	 * 
	 * @param contractCode
	 * @return
	 * @throws Exception
	 */
	private List<TCMmContractDTO> searchTCMmContract(String contractCode) throws Exception {
		List<TCMmContractDTO> dtos = null;
		Map<String, Object> searchParams = new HashMap<String, Object>();
		TCMmContractDTO dto = new TCMmContractDTO();
		dto.setContractCode(contractCode);
		searchParams.put("dto", dto);
		dtos = tcMmContractService.searchTCMmContract(searchParams);

		return dtos;
	}

	/**
	 * @description 保存额度申请信息（贷款）
	 * 
	 * @param quotaCode
	 * @param quotaSum
	 * @param startDate
	 * @param invalidDate
	 * @param quotaType
	 * @param contractCode
	 * @param cooperorgCode
	 * @param quotaStatus
	 * @param validateState
	 * @throws Exception
	 */
	private void insertQuotaInfo(String quotaCode, BigDecimal quotaSum, Date startDate, Date invalidDate, String quotaType, String contractCode,
			String cooperorgCode, String quotaStatus, String validateState) throws Exception {

		// 组装额度申请dto
		QuotaDto quotaDto = new QuotaDto();
		quotaDto.setQuotaCode(quotaCode);// 申请流水号
		quotaDto.setQuotaSum(quotaSum);// 申请金额
		quotaDto.setStartDate(startDate);// 起始日期
		quotaDto.setInvalidDate(invalidDate);// 失效日期
		quotaDto.setQuotaType(quotaType);// 额度申请类型
		quotaDto.setContractCode(contractCode);// 合约编号
		quotaDto.setCooperorgCode(cooperorgCode);// 合作机构名称
		quotaDto.setQuotaStatus(quotaStatus);// 申请状态
		quotaDto.setValidateState(validateState);// 数据有效性
		// 保存额度申请
		Map<String, Object> saveLoanParams = new HashMap<String, Object>();
		saveLoanParams.put("dto", quotaDto);
		quotaDao.insertQuota(saveLoanParams);
	}
}
